import { ref, onBeforeMount, nextTick } from 'vue'
import { useUser } from '@/composition/useUser';
import { useLoading } from '@/composition/useLoading'

import router from '@/plugins/router';
import { uploadApi } from '@/plugins/http/api/common'
import { setUserExtInfoApi } from '@/plugins/http/api/user'
import { useToast } from '@/composition/useToast'

const { showLoading, closeLoading } = useLoading()
const { successToast, errorToast } = useToast()


// let router;
// let userInfo;
// onBeforeMount(() => {

// })

// export const bgLoaded = () => {
//     let bgbox = document.querySelector('.bgbox')
//     bgbox.style.display = 'block' // 先隐藏

//     bgbox.style.transform = 'scale(1.1)';
//     // await nextTick()
//     // bgbox.style.transform = 'scale(1.0)';
//     setTimeout(() => {
//         bgbox.style.transform = 'scale(1.0)';
//     }, 1000);
// }

// const bgShowUrlList = [];
// export const getBgShowUrlList = async () => {
//     const { user } = useUser();
//     let userInfo = user.value;
//     let deviceType = getDeviceType();

//     let bgInfo = userInfo?.extInfo?.bg[deviceType];

//     let showType = bgInfo?.showType;
//     if (showType == 'url') {
//         const urls = bgInfo.urls || [];
//         const urlsChecked = urls.filter(item => item.checked);

//         const imgCacheSize = 5;
//         for (let i = 0; i < imgCacheSize - bgShowUrlList.length; i++) {

//             let showUrl;
//             if (urlsChecked && urlsChecked.length > 0) {
//                 let size = urlsChecked.length;
//                 let index = parseInt(Math.random() * size); // 生成 [0,size-1] 的随机整数
//                 showUrl = urlsChecked[index].url;
//             }

//             let now = new Date().getTime() + '-' + i;
//             if (showUrl) {
//                 // console.log(showUrl)
//                 if (showUrl.indexOf('?') > -1) {
//                     showUrl += '&time=' + now
//                 } else {
//                     showUrl += '?time=' + now
//                 }
//                 await initImg(showUrl)
//                 bgShowUrlList.push(showUrl);
//             }
//         }
//     }
//     console.log(bgShowUrlList)
//     return bgShowUrlList;
// }

// export const initImg = async (imgUrl) => {
//     return new Promise((resolve) => {
//         let img = new Image();
//         img.src = imgUrl;
//         img.onload = () => {
//             resolve()
//         }
//     })
// }


// export const setBg = async () => {
//     const { user } = useUser();

//     let bgbox = document.querySelector('.bgbox')
//     if (!bgbox) {
//         return
//     }

//     let userInfo = user.value;

//     let deviceType = getDeviceType();

//     let bgInfo = userInfo?.extInfo?.bg[deviceType];

//     let showType = bgInfo?.showType;
//     if (showType == 'url') {
//         await getBgShowUrlList()
//         console.log(bgShowUrlList)
//         let showUrl = bgShowUrlList[0]
//         bgShowUrlList.shift() // 删除第一个

//         bgbox.style.backgroundImage = 'url(' + showUrl + ')'
//         bgbox.style.backgroundColor = ''

//     } else if (showType == 'color') {
//         bgbox.style.backgroundImage = ''
//         bgbox.style.backgroundColor = bgInfo.color
//         resolve();
//     } else {
//         bgbox.style.backgroundImage = ''
//         bgbox.style.backgroundColor = ''
//         resolve();
//     }
// }


// let bgInterval;
// export const setBg = async () => {
//     // return

//     new Promise((resolve) => {
//         const { user } = useUser();

//         let bgbox = document.querySelector('.bgbox')
//         if (!bgbox) {
//             return
//         }
//         // bgbox.style.display = 'none' // 先隐藏

//         let userInfo = user.value;

//         let deviceType = getDeviceType();

//         let bgInfo = userInfo?.extInfo?.bg[deviceType];

//         let showType = bgInfo?.showType;
//         if (showType == 'url') {
//             const urls = bgInfo.urls || [];
//             const urlsChecked = urls.filter(item => item.checked);

//             let showUrl;
//             if (urlsChecked && urlsChecked.length > 0) {
//                 let size = urlsChecked.length;
//                 let index = parseInt(Math.random() * size); // 生成 [0,size-1] 的随机整数
//                 showUrl = urlsChecked[index].url;
//             }

//             let now = new Date();
//             if (showUrl) {
//                 // console.log(showUrl)
//                 if (showUrl.indexOf('?') > -1) {
//                     showUrl += '&time=' + now.getTime()
//                 } else {
//                     showUrl += '?time=' + now.getTime()
//                 }
//                 // console.log(showUrl)
//             }

//             let img = new Image();
//             img.src = showUrl;
//             img.onload = () => {
//                 bgbox.style.backgroundImage = 'url(' + showUrl + ')'
//                 bgbox.style.backgroundColor = ''
//                 resolve();
//             }
//         } else if (showType == 'color') {
//             bgbox.style.backgroundImage = ''
//             bgbox.style.backgroundColor = bgInfo.color
//             resolve();
//         } else {
//             bgbox.style.backgroundImage = ''
//             bgbox.style.backgroundColor = ''
//             resolve();
//         }
//     })

//     // bgbox.style.transform = 'scale(1.1)';
//     // // await nextTick()
//     // // bgbox.style.transform = 'scale(1.0)';
//     // setTimeout(() => {
//     //     bgbox.style.transform = 'scale(1.0)';
//     // }, 0);

// }


// let bgInterval;
// export const setBg = (showBgEle) => {
//     // return
//     const { user } = useUser();

//     let bgbox = document.querySelector('.bgbox')
//     if (!bgbox) {
//         return
//     }
//     // bgbox.style.display = 'none' // 先隐藏

//     let userInfo = user.value;

//     let deviceType = getDeviceType();

//     let bgInfo = userInfo?.extInfo?.bg[deviceType];

//     let showType = bgInfo?.showType;
//     if (showType == 'url') {
//         const autoChangeBg = bgInfo.autoChangeBg || {};

//         const urls = bgInfo.urls || [];
//         const urlsChecked = urls.filter(item => item.checked);

//         let showUrl;
//         if (urlsChecked && urlsChecked.length > 0) {
//             let size = urlsChecked.length;
//             let index = parseInt(Math.random() * size); // 生成 [0,size-1] 的随机整数
//             showUrl = urlsChecked[index].url;
//         }

//         let now = new Date();
//         if (showUrl) {
//             // console.log(showUrl)
//             if (showUrl.indexOf('?') > -1) {
//                 showUrl += '&time=' + now.getTime()
//             } else {
//                 showUrl += '?time=' + now.getTime()
//             }
//             // console.log(showUrl)
//         }

//         let img = new Image();
//         img.src = showUrl;
//         img.onload = () => {
//             bgbox.style.backgroundImage = 'url(' + showUrl + ')'
//             bgbox.style.backgroundColor = ''
//             showBgEle.value = true
//         }

//         if (bgInterval) {
//             clearInterval(bgInterval)
//         }
//         if (autoChangeBg.isOpen && autoChangeBg.interval) {
//             bgInterval = setInterval(() => {
//                 showBgEle.value = false
//                 setBg(showBgEle)
//             }, autoChangeBg.interval * 1000);
//         }

//     } else if (showType == 'color') {
//         bgbox.style.backgroundImage = ''
//         bgbox.style.backgroundColor = bgInfo.color
//         showBgEle.value = true
//     } else {
//         bgbox.style.backgroundImage = ''
//         bgbox.style.backgroundColor = ''
//         showBgEle.value = true
//     }
// }



export const bgColors = [
    {
        color: '#C7EDCC',
        name: '豆沙绿'
    },
    {
        color: '#FFFFFF',
        name: '银河白'
    },
    {
        color: '#FAF9DE',
        name: '杏仁黄'
    },
    {
        color: '#FFF2E2',
        name: '秋叶褐'
    },
    {
        color: '#FDE6E0',
        name: '胭脂红'
    },
    {
        color: '#E3EDCD',
        name: '青草绿'
    },
    {
        color: '#DCE2F1',
        name: '海天蓝'
    },
    {
        color: '#E9EBFE',
        name: '葛巾紫'
    },
    {
        color: '#EAEAEF',
        name: '极光灰'
    },
    {
        color: '#B7E8BD',
        name: '苹果绿'
    },
    {
        color: '#CCE8CF',
        name: '豆沙绿-略暗'
    }
];

export const isType = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Array]') {
        return 'Array';
    } else if (type == '[object Object]') {
        return "Object"
    } else {
        return 'param is no object type';
    }
}

export const isObject = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Object]') {
        return true;
    }
    return false;
}

export const isArray = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Array]') {
        return true;
    }
    return false;
}

export const isString = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object String]') {
        return true;
    }
    return false;
}

export const isNumber = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Number]') {
        return true;
    }
    return false;
}

export const isBoolean = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Boolean]') {
        return true;
    }
    return false;
}

export const isUndefined = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Undefined]') {
        return true;
    }
    return false;
}

export const isDate = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Date]') {
        return true;
    }
    return false;
}

export const isFunction = (obj) => {
    var type = Object.prototype.toString.call(obj);
    if (type == '[object Function]') {
        return true;
    }
    return false;
}

export const compreObj = (obj1, obj2) => {
    // 判断类型是否一致
    if (
        (isUndefined(obj1) && !isUndefined(obj2))
        || (isObject(obj1) && !isObject(obj2))
        || (isArray(obj1) && !isArray(obj2))
        || (isString(obj1) && !isString(obj2))
        || (isNumber(obj1) && !isNumber(obj2))
        || (isBoolean(obj1) && !isBoolean(obj2))
        || (isDate(obj1) && !isDate(obj2))
    ) {
        console.log('compreObj:类型不一致');
        return false;
    }

    if (isUndefined(obj1)) {
        return true;
    }

    let result = true;

    if (isObject(obj1)) {
        // 先判断 对象 key 的个数是否一致
        if (Object.keys(obj1).length !== Object.keys(obj2).length) {
            console.log('compreObj:对象key的个数不一致');
            return false;
        }
        for (let key in obj1) {
            if (Object.prototype.hasOwnProperty.call(obj2, key)) {
                // 获取 对应 key 的 value 判断
                result = compreObj(obj1[key], obj2[key]);
                if (!result) {
                    // 如果 失败 直接 返回即可
                    return result;
                }
            } else {
                console.log('compreObj:对应的key没有');
                return false;
            }
        }
    } else if (isArray(obj1)) {
        // 先判断 数组长度是否一致
        if (obj1.length !== obj2.length) {
            console.log('compreObj:数组长度不一致');
            return false;
        }
        for (let i in obj1) {
            result = compreObj(obj1[i], obj2[i]);
            if (!result) {
                // 如果 失败 直接 返回即可
                return result;
            }
        }
    } else {
        if (obj1 !== obj2) {
            console.log('compreObj:值不相等');
            return false;
        }
    }
    return result;
}

export const isPhone = () => {
    const info = navigator.userAgent
    return /mobile/i.test(info)
}


export const getDeviceType = () => {
    if (isPhone()) {
        return 'mobile';
    }
    return 'pc';
}


export const generateUUID = () => {
    let d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}


export const getReqParam = (name) => {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    const r = window.location.search.substring(1).match(reg);//search,查询？后面的参数，并匹配正则
    if (r != null) return unescape(r[2]);
    return null;
}


export const goHome = () => {
    router.push('/');
}


export const go2Router = (name) => {
    router.push({ name });
}

export const copyJSON = (json) => {
    return JSON.parse(JSON.stringify(json));
}

export const isNull = (str) => {
    return str == undefined || str == null;
}

export const isEmpty = (str) => {
    return str == undefined || str == null || str == '';
}

export const isNotNull = (str) => {
    return !isNull(str);
}

export const isNotEmpty = (str) => {
    return !isEmpty(str);
}

export const go2Link = (url, target) => {
    let a = document.createElement('a');
    a.href = url;
    if (target) {
        a.target = target;
    } else {
        a.target = '_blank';
    }
    a.click();
    a.remove();
}

export const scrollToTop = () => {
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    });
}

// async 用于申明一个函数是异步的，await 等待异步请求完成，await只能在async方法中使用。
export const uploadFile = async (file) => {
    const forms = new FormData();
    forms.append('file', file);
    forms.append('appCode', 'F0FB4BED6B664CFEBBB30A688A4C8E3F');
    const res = await uploadApi(forms);
    if (res.code != '0') {
        showNotify({ type: 'danger', message: '上传失败' });
        return;
    }
    return res.data;
}

export const getFileDataURL = async (file) => {
    const fileReader = new FileReader();
    showLoading();
    fileReader.readAsDataURL(file);
    return new Promise((resolve, reject) => {
        fileReader.onload = () => {
            closeLoading();
            // console.log(fileReader.result);
            resolve(fileReader.result);
        }
    })
}


export const saveUser2Db = () => {
    const { user, loggedIn } = useUser();
    if (!loggedIn.value) {
        successToast('保存设置到本地成功');
        return;
    }
    // save data to db
    let setUserExtInfoData = {
        appCode: 'F0FB4BED6B664CFEBBB30A688A4C8E3F',
        param: {
            userSet: user.value.extInfo
        }
    };
    setUserExtInfoApi(setUserExtInfoData).then(setUserExtInfoDataRes => {
        if (setUserExtInfoDataRes.code != '0') {
            errorToast('保存设置到云端失败:' + setUserExtInfoDataRes.message)
            return;
        }
        successToast('保存设置到云端成功');
    })
}



export const refresh = () => {
    window.location.reload();
}
